package com.angel.kuaidi.activity;

import java.util.ArrayList;
import java.util.HashMap;

import com.angel.kuaidi.R;
import com.angel.kuaidi.db.DB;
import com.angel.kuaidi.entity.HistoryInfo;
import com.angel.kuaidi.entity.WuliuCompanyInfo;
import com.angel.kuaidi.entity.WuliuInfo;
import com.angel.kuaidi.entity.WuliuInfoItem;
import com.angel.kuaidi.json.handler.WuliuInfoHandler;
import com.angel.kuaidi.net.HttpTools;
import com.angel.kuaidi.utils.Utils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class KuaidiDetailActivity extends BaseActivity {

	public final String[] STATE = { "在途中", "已发货", "疑难件", "已签收", "已退货" };

	LinearLayout ll_info;
	TextView tv_orderNum;
	TextView tv_company;
	TextView tv_state;
	TextView tv_updatetime;
	LinearLayout ll_list;
	TextView tv_none;

	LayoutInflater inflater;

	private static final String[] URL_S = { "http://m.kuaidi100.com/query?", "http://www.kuaidi100.com/query?" };

	String type = "";
	String postid = "";
	int from = 0;

	WuliuCompanyInfo company;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			//
			WuliuInfo w = (WuliuInfo) msg.obj;
			initList(w.infos);

			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setView(R.layout.wuliu_detail);

		initData();
		initView();
		registerListener();
		display();
		adView();
	}
	private void adView() {

		View v = findViewById(R.id.adview);
		SharedPreferences share = mContext.getSharedPreferences("adview_flag", Context.MODE_PRIVATE);
		if (share.getBoolean("flag", false)) {
			v.setVisibility(View.VISIBLE);
		} else {
			v.setVisibility(View.GONE);
		}
	}

	private void initData() {
		inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		company = (WuliuCompanyInfo) getIntent().getSerializableExtra("company");
		// 赋值
		postid = getIntent().getStringExtra("postid");
		// 从哪里进来
		from = getIntent().getIntExtra("from", 0);
		type = company.pinyinname;
		if (postid == null || "".equals(postid)) {
			finish();
			Utils.toast(mContext, "传参错误!");
		}
		if (company == null) {
			finish();
			Utils.toast(mContext, "传参错误!");
		}
	}

	private void initView() {

		if (from == 0) {
			setTitle("返回", "快递跟踪详情", "查询历史");
		} else {
			setTitle("返回", "历史跟踪详情", "");
		}

		ll_info = (LinearLayout) findViewById(R.id.ll_info);
		tv_orderNum = (TextView) findViewById(R.id.tv_orderNum);
		tv_company = (TextView) findViewById(R.id.tv_company);
		tv_state = (TextView) findViewById(R.id.tv_state);
		tv_updatetime = (TextView) findViewById(R.id.tv_updatetime);
		ll_list = (LinearLayout) findViewById(R.id.ll_list);
		tv_none = (TextView) findViewById(R.id.tv_none);
	}

	private void registerListener() {

		tv_none.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new RequestDataAsy().execute();
			}
		});

	}

	private void display() {
		new RequestDataAsy().execute();
	}

	private void initList(ArrayList<WuliuInfoItem> list) {

		ll_list.removeAllViews();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				WuliuInfoItem wiif = list.get(i);
				View view = inflater.inflate(R.layout.wuliu_detail_item, null);

				TextView tv_ftime = (TextView) view.findViewById(R.id.tv_ftime);
				TextView tv_context = (TextView) view.findViewById(R.id.tv_context);

				tv_ftime.setText(wiif.ftime);
				tv_context.setText(wiif.context);
				if (i % 2 == 1) {
					// view.setBackgroundColor(0xfff3f3f3);
					view.setBackgroundColor(0xfcefeff8);
				}

				ll_list.addView(view);
			}
		} else {
			TextView tv = new TextView(mContext);
			LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			param.topMargin = (int) (50 * getResources().getDisplayMetrics().density);
			tv.setText("暂无跟踪信息");
			tv.setTextSize(16);
			tv.setGravity(Gravity.CENTER);
			tv.setTextColor(0x313232);
			ll_list.addView(tv, param);
		}
	}

	class RequestDataAsy extends AsyncTask<Void, Void, WuliuInfo> {

		Dialog dialog = null;

		@Override
		protected void onCancelled() {
			super.onCancelled();
			ll_info.setVisibility(View.GONE);
			tv_none.setVisibility(View.VISIBLE);
			tv_none.setText("点击重新查询");

		}

		@Override
		protected void onPostExecute(final WuliuInfo w) {

			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}

			if (w != null) {

				if ("200".equals(w.status) || "1".equals(w.status)) {
					ll_info.setVisibility(View.VISIBLE);
					tv_none.setVisibility(View.GONE);
					//
					tv_orderNum.setText(w.nu);
					tv_company.setText(company.chinesename);
					tv_state.setText(STATE[w.state]);
					tv_updatetime.setText(w.updatetime);
					//
					Message msg = handler.obtainMessage();
					msg.obj = w;
					handler.sendMessageDelayed(msg, 20);
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {

							DB.getInstance(mContext).delete(HistoryInfo.class, "postid=" + postid);
							HistoryInfo hi = new HistoryInfo();
							hi.postid = postid;
							hi.chinesename = company.chinesename;
							hi.pinyinname = company.pinyinname;
							hi.status = w.state + "";
							hi.time = System.currentTimeMillis() + "";
							DB.getInstance(mContext).add(hi);
						}
					}, 1000);

				} else if ("0".equals(w.status)) {
					ll_info.setVisibility(View.GONE);
					tv_none.setVisibility(View.VISIBLE);
					tv_none.setText("暂无运单结果");
				} else {
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// 删除无效记录
							DB.getInstance(mContext).delete(HistoryInfo.class, "postid=" + postid + " and chinesename=''");
						}
					}, 1000);
					ll_info.setVisibility(View.GONE);
					tv_none.setVisibility(View.VISIBLE);
					tv_none.setText("暂无运单结果,请核对信息。您选择的物流公司是：" + company.chinesename + "。" + "您输入的运单号为:" + postid + "。");
				}
			} else {
				ll_info.setVisibility(View.GONE);
				tv_none.setVisibility(View.VISIBLE);
				tv_none.setText("网络异常,请点击重新加载");
			}
			super.onPostExecute(w);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = Utils.showProcessDialog(mContext, "正在查询,请稍候...");
			dialog.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					cancel(true);
				}
			});
		}

		@Override
		protected WuliuInfo doInBackground(Void... params) {

			String p = "type=" + type + "&postid=" + postid;
			int i = (int) (Math.random() * 10);
			String url = URL_S[i % 2];
			WuliuInfo wi = (WuliuInfo) HttpTools.getObjectWithJson(url + p, new WuliuInfoHandler());
			return wi;
		}
	}

	@Override
	protected void onRightBtnClick() {
		super.onRightBtnClick();

		Intent intent = new Intent();
		intent.setClass(mContext, HistoryActivity.class);
		startActivity(intent);
		finish();
	}

}
